<!DOCTYPE html>
<html>
	<head>
		<meta charset="UTF-8">
		<title></title>
	</head>
	<!--
    	作者：zyl
    	时间：2017-05-27
    	描述：isPointInPath() 方法
    	
    定义和用法
	isPointInPath() 方法返回 true，如果指定的点位于当前路径中；否则返回 false。
	JavaScript 语法：
	context.isPointInPath(x,y);
	
	参数值
		参数			描述
		x		测试的 x 坐标
		y		测试的 y 坐标
    -->
	<body>
		<span style="display: block;height:35px;text-align:center;line-height:35px; font-size: 28px ;color: red;">点击小球变红</span>
		<canvas id="canvas" style="border: 2px solid #ccc; display: block;margin: 50px auto;">
			
		</canvas>
	</body>
	<script>
		  var canvas = document.getElementById("canvas");   
        canvas.width = 800;   
        canvas.height = 600;   
        var context = canvas.getContext("2d");  
        
        var balls =[];
        for(var i=0;i<10;i++){
        	var abll ={x:Math.random()*canvas.width,
        				y:Math.random()*canvas.height,
        					r:Math.random()*50+20};
        					balls[i]=abll;
        	
        }
        draw();
        canvas.addEventListener("mouseup",detect);//鼠标点击事件
        canvas.addEventListener("mousemove",function(event){//鼠标移动事件
        	  var x =event.clientX-canvas.getBoundingClientRect().left;
        	var y =event.clientY-canvas.getBoundingClientRect().top;
        	overDraw(x,y);
        	
        });
        
        function draw(){  	//绘制蓝色的球
	        for(var i =0;i<balls.length;i++){
	      context.beginPath();
	      // context.arc(balls[i]['x'],balls[i]['y'],balls[i]['r'],0,2*Math.PI);
	      	context.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2);
	       context.fillStyle="blue";
	       context.fill();
        }  
    }
          function overDraw(x,y){//鼠标移动的地方绘制
	    	context.clearRect(0,0,canvas.width,canvas.height);//
	    	for(var i=0;i<balls.length;i++){
	    		context.beginPath();
	    			context.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2);
	    			if(context.isPointInPath(x,y)){//鼠标移入绘制黄色的球
	    				context.fillStyle="yellow";
	    				context.fill();
	    			}else{//移除在绘制蓝色的球
	    			context.fillStyle = "blue";//原来的颜色
	    			context.fill();
	    			}
	    	}
	    	
	    }
        function detect(event){
        	//获取鼠标在canvas中的点击位置
        	var x =event.clientX-canvas.getBoundingClientRect().left;
        	var y =event.clientY-canvas.getBoundingClientRect().top;
        	
        	for(var i=0;i<balls.length;i++){//遍历数组
        		context.beginPath();
        		context.arc(balls[i].x,balls[i].y,balls[i].r,0,Math.PI*2);
        		if(context.isPointInPath(x,y)){//判断是否点击到了圆上
        			context.fillStyle="red";
        			context.fill();
        		}
        	}
        	
        }
        
	</script>
</html>
